package com.agriculture.controller;

import com.agriculture.domain.Inventory;
import com.agriculture.exception.BusinessException;
import com.agriculture.service.OrderService;
import com.agriculture.domain.Order;
import com.agriculture.service.DealerService;
import com.agriculture.domain.Product;
import com.agriculture.common.Result;
import com.agriculture.domain.User;
import com.agriculture.dto.Order.OrderDTO;
import com.agriculture.dto.request.ImportOrderRequest;
import com.agriculture.service.InventoryService;
import com.agriculture.common.PageResult;
import com.agriculture.mapper.ProductMapper;
import com.agriculture.dto.InventoryProductDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@CrossOrigin
@RestController
@RequestMapping("/api/dealer")
public class DealerController {

    private static final Logger log = LoggerFactory.getLogger(DealerController.class);
    @Autowired
    private DealerService dealerService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private ProductMapper productMapper;
    
    /**
     * 获取可购买农产品列表
     */
    @GetMapping("/purchase-products")
    public Result getPurchaseProducts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String ownerName,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder) {
            
        try {
            // 获取产品列表
            List<Product> products = dealerService.getPurchaseProducts(search, category, ownerName, 
                                                                 minPrice, maxPrice, sortBy, sortOrder);
            
            // 构造分页响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("items", products);
            response.put("total", products.size());
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取农产品列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取农产品详情
     */
    @GetMapping("/products/{id}/detail") 
    public Result getProductDetail(@PathVariable Long id) {
        Product product = dealerService.getProductDetail(id);
        if (product == null) {
            return Result.error("商品不存在");
        }
        return Result.success(product);
    }

    /**
     * 创建订单
     */
    @PostMapping("/purchase-orders")
    public Result createOrder(@RequestBody OrderDTO orderDTO) {
        log.info("orderDTO :{}",orderDTO);
        try {
            Order order = dealerService.createOrder(orderDTO);
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("创建订单失败:" + e.getMessage());
        }
    }

    /**
     * 取消采购订单
     */
    @PostMapping("/purchase-orders/{id}/cancel")
    public Result cancelPurchaseOrder(@PathVariable Long id, @RequestBody String reason) {
        try {
            dealerService.cancelPurchaseOrder(id, reason);
            return Result.success();
        } catch (Exception e) {
            return Result.error("取消订单失败:" + e.getMessage());
        }
    }

    /**
     * 确认收货
     */
    @PostMapping("/purchase-orders/{id}/confirm-receipt")
    public Result confirmReceipt(@PathVariable Long id) {
        try {
            dealerService.confirmReceipt(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("确认收货失败:" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<List<User>> list(Integer pageNum, Integer pageSize) {
        List<User> dealers = dealerService.listDealers();
        return Result.success(dealers);
    }

    @PostMapping("/stocks/import")
    public Result<?> importOrderToInventory(@RequestBody ImportOrderRequest request) {
        try {
            // 参数校验
            if (request.getOrderId() == null || request.getOwnerId() == null) {
                return Result.error("参数不完整");
            }

            // 如果 operator 为空，设置默认值
            String operator = request.getOperator();
            if (operator == null || operator.trim().isEmpty()) {
                operator = "dealer";
            }

            orderService.importOrderToInventory(
                request.getOrderId(),
                request.getOwnerId(),
                operator
            );
            return Result.success("导入成功");
        } catch (Exception e) {
            log.error("导入库存失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/stocks")
    public Result<PageResult<Inventory>> getStocks(
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(defaultValue = "10") int pageSize,
        @RequestParam(required = false) String search,
        @RequestParam Long userId
    ) {
        try {
            log.info("获取库存列表参数: page={}, pageSize={}, search={}, userId={}", 
                page, pageSize, search, userId);
            
            PageResult<Inventory> result = inventoryService.getStockList(userId, search, page, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取库存列表失败", e);
            return Result.error("获取库存列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/inventory-products")
    public Result<PageResult<InventoryProductDTO>> getInventoryProducts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String category,
            @RequestParam Long userId) {
        try {
            int offset = (page - 1) * pageSize;
            List<InventoryProductDTO> products = productMapper.selectInventoryProducts(
                search,
                category,
                userId,
                offset,
                pageSize
            );
            int total = productMapper.countInventoryProducts(search, category, userId);
            return Result.success(new PageResult<>(products, total));
        } catch (Exception e) {
            log.error("获取库存商品列表失败", e);
            return Result.error("获取库存商品列表失败: " + e.getMessage());
        }
    }

    @PostMapping("/products")
    public Result<?> createProduct(@RequestBody Product product, @RequestParam Long userId) {
        try {
            // 直接使用传入的userId
            Product createdProduct = dealerService.createProduct(userId, product);
            return Result.success(createdProduct);
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建商品失败", e);
            return Result.error("创建商品失败");
        }
    }
}
